﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using RssReaderTemplate.Model;
using Microsoft.Phone.Reactive;

namespace RssReaderTemplate
{
    public partial class NetworkNotifier : UserControl
    {
        public NetworkNotifier()
        {
            // Required to initialize variables
            InitializeComponent();
        }



        public bool IsNetworkAvailable
        {
            get { return (bool)GetValue(IsNetworkAvailableProperty); }
            set { SetValue(IsNetworkAvailableProperty, value); }
        }

        // Using a DependencyProperty as the backing store for IsNetworkAvailable.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty IsNetworkAvailableProperty =
            DependencyProperty.Register("IsNetworkAvailable", typeof(bool), typeof(NetworkNotifier), null);


        IDisposable _subscription;

        public NetworkMonitor NetworkMonitor
        {
            get { return (NetworkMonitor)GetValue(NetworkMonitorProperty); }
            set 
            {
                SetValue(NetworkMonitorProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for NetworkMonitor.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty NetworkMonitorProperty =
            DependencyProperty.Register("NetworkMonitor", typeof(NetworkMonitor), typeof(NetworkNotifier), new PropertyMetadata(NetworkMonitorChanged));

        private static void NetworkMonitorChanged(DependencyObject instance, DependencyPropertyChangedEventArgs args)
        {
            NetworkNotifier notifier = instance as NetworkNotifier;
            if (notifier != null && notifier._subscription != null)
            {
                notifier._subscription.Dispose();
            }
            else if (notifier != null)
            {
                notifier._subscription = ((NetworkMonitor)args.NewValue)
                    .ObserveOnDispatcher()
                    .Subscribe(x => notifier.Visibility = x == true ? Visibility.Collapsed : Visibility.Visible);
            }
        }



    }
}